package com.zfsbs.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.model.SbsPrinterData;
import com.tool.utils.dialog.LoadingDialog;
import com.tool.utils.utils.ALog;
import com.tool.utils.utils.FyAidlUtils;
import com.tool.utils.utils.LogUtils;
import com.tool.utils.utils.SPUtils;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.zfsbs.R;
import com.zfsbs.adapter.MyMenuListAdapter;
import com.zfsbs.common.CommonFunc;
import com.zfsbs.config.Constants;
import com.zfsbs.config.EnumConstsSbs;
import com.zfsbs.core.action.FyPrintUtils;
import com.zfsbs.core.myinterface.ActionCallbackListener;
import com.zfsbs.model.Couponsn;
import com.zfsbs.model.MemberTransAmountResponse;
import com.zfsbs.model.Menu;
import com.zfsbs.model.SmFyResponse;
import com.zfsbs.model.TransUploadRequest;
import com.zfsbs.model.TransUploadResponse;
import com.zfsbs.myapplication.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;


public class ZfPayPreauth2Activity extends BaseActivity {
	private String TAG = "SysMainActivity";

	private List<Menu> list = new ArrayList<Menu>();
//	private MyGridView gridView;
//	private MyMenuAdapter adapter;
	private ListView listView;
	private MyMenuListAdapter adapter;

	private List<SbsPrinterData> allData;
	private String orderNo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_system);
//		AppManager.getAppManager().addActivity(this);
		initTitle("系统设置");
		initView();
	}

	private void initView() {





		for (int i = 0; i < EnumConstsSbs.PreauthType.values().length; i++){
			Menu menu = new Menu();
			menu.setBg(EnumConstsSbs.PreauthType.values()[i].getBg());
			menu.setName(EnumConstsSbs.PreauthType.values()[i].getName());
			list.add(menu);
		}



		listView = (ListView) findViewById(R.id.id_gridview);
		adapter = new MyMenuListAdapter(this, list, R.layout.my_list_item);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.e(TAG, "onItemClick " + position);
				// 下拉刷新占据一个位置
				int index = EnumConstsSbs.PreauthType.getCodeByName(list.get(position).getName());
				switch (index){
					case 1:
						Intent intent19 = new Intent();
						intent19.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

						//包名     包名+类名（全路径）
						Bundle bundle = new Bundle();
						intent19.putExtra("transName", "预授权");
						startActivityForResult(intent19,  Constants.PAY_WAY_PREAUTH);
						break;
					case 2:
						Intent intent20 = new Intent();
						intent20.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

						//包名     包名+类名（全路径）
						intent20.putExtra("transName", "预授权撤销");
						startActivityForResult(intent20, Constants.PAY_WAY_AUTHCANCEL);
						break;
					case 3:
						Intent intent21 = new Intent();
						intent21.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

						//包名     包名+类名（全路径）
						intent21.putExtra("transName", "预授权完成（请求）");
						startActivityForResult(intent21, Constants.PAY_WAY_AUTHCOMPLETE);
						break;
					case 4:
						Intent intent22 = new Intent();
						intent22.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

						//包名     包名+类名（全路径）
						intent22.putExtra("transName", "预授权完成撤销");
						startActivityForResult(intent22, Constants.PAY_WAY_VOID_AUTHCOMPLETE);
						break;
				}
			}
		});
	}


	@SuppressLint("WrongConstant")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("Fuiou", "resultCode--返回值："+resultCode);
		Log.i("TAG", "resultCode--返回值："+resultCode);
		switch (resultCode) {
			case Activity.RESULT_CANCELED:
				String reason = "";
				String traceNo = "";
				String batchNo = "";
				String ordernumber = "";
				if (data != null) {
					Bundle b = data.getExtras();
					if (b != null) {
						reason = (String) b.get("reason");
						traceNo = (String)b.getString("traceNo");
						batchNo = (String)b.getString("batchNo");
						ordernumber = (String)b.getString("ordernumber");
					}
				}
				if (reason != null) {
					Log.d("reason", reason);
					Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
				}
				Log.w("TAG", "失败返回值--reason--返回值："+reason+"/n 凭证号："+traceNo+"/n 批次号："+batchNo+"/n 订单号："+ordernumber);

//				etBack.setText("失败："+reason+"/n 凭证号："+traceNo+"/n 批次号："+batchNo+"/n 订单号："+ordernumber);
				break;
			case Activity.RESULT_OK:
				String print = data.getStringExtra("reason");//打印成功返回数据
				Log.w("TAG", "成功返回值--reason--返回值："+print);

				String b = data.getStringExtra("batchNo");//批次号
				String c = data.getStringExtra("traceNo");//流水号
				String d = data.getStringExtra("cardNo");//卡号

				String e = data.getStringExtra("merchantId");//商户号
				String f = data.getStringExtra("terminalId");//终端号

				String g = data.getStringExtra("referenceNo");//参考号
				String h = data.getStringExtra("issue");//发卡行
				String i = data.getStringExtra("type");//卡类型
				String j = data.getStringExtra("date");//日期
				String k = data.getStringExtra("time");//时间

				String l = data.getStringExtra("wireless.apn");//apn
				String m = data.getStringExtra("wireless.username");//用户名
				String n = data.getStringExtra("wireless.password");//密码
				String o = data.getStringExtra("wireless.apnEnabled");//Apn是否开启
				String p = data.getStringExtra("merchantName");//商户名

				String r = data.getStringExtra("oldReferenceNo");//原参考号

				String t = data.getStringExtra("orderNumber");
				String tzfb = data.getStringExtra("zfbOrderNumber");
				String twx = data.getStringExtra("wxOrderNumber");

				String u = data.getStringExtra("oldOrderNumber");
				String sWx = data.getStringExtra("wxOldOrderNumber");
				String sZfb = data.getStringExtra("zfbOldOrderNumber");

				String wMb = data.getStringExtra("zfbMbOldOrderNumber");
				String zMb = data.getStringExtra("wxMbOldOrderNumber");

				String tui = data.getStringExtra("tuiOldOrderNumber");

				String settleData = data.getStringExtra("settleJson");
				String json = data.getStringExtra("json");

				String return_Code = data.getStringExtra("return_txt");//扫码返回数据

				String authorizationCode = data.getStringExtra("authorizationCode");//预授权 授权码

				String backOldReferenceNo = data.getStringExtra("backOldReferenceNo");//退货的原参考号

				String referenceNoSuccess = data.getStringExtra("referenceNoSuccess");//订单查询返回参考号

				String oldReferenceNoSuccess = data.getStringExtra("oldReferenceNoSuccess");//订单查询返回原参考号

				String amount = data.getStringExtra("amount");//金额

				String acqId = data.getStringExtra("acqId");//收单行

				String expiredDate = data.getStringExtra("expiredDate");//卡有效期

				String oldTrace = data.getStringExtra("oldTrace"); //原凭证号

				JSONObject jsO = new JSONObject();
				try {
					jsO.put("reason", print);
					jsO.put("batchNo", b);//批次号
					jsO.put("traceNo", c);//流水号
					jsO.put("cardNo", d);//卡号
					jsO.put("merchantId", e);//商户号
					jsO.put("terminalId", f);//终端号
					jsO.put("referenceNo", g);//参考号
					jsO.put("issue", h);//发卡行
					jsO.put("type", i);//卡类型
					jsO.put("date", j);//日期
					jsO.put("time", k);//时间
					jsO.put("wireless.apn", l);//apn
					jsO.put("wireless.username", m);//用户名
					jsO.put("wireless.password", n);//密码
					jsO.put("wireless.apnEnabled", o);//Apn是否开启
					jsO.put("merchantName", p);//商户名
					jsO.put("oldReferenceNo", r);//原参考号
					jsO.put("backOldReferenceNo", backOldReferenceNo);//退货原参考号
					jsO.put("orderNumber", t);//消费订单号
					jsO.put("zfbOrderNumber", tzfb);//支付宝消费订单号
					jsO.put("wxOrderNumber", twx);//微信消费订单号
					jsO.put("oldOrderNumber", u);//原消费订单号
					jsO.put("wxOldOrderNumber", sWx);//原支付宝消费订单号
					jsO.put("zfbOldOrderNumber", sZfb);//原微信消费订单号
					jsO.put("zfbMbOldOrderNumber",wMb);//原支付宝末笔订单号
					jsO.put("wxMbOldOrderNumber", zMb);//原微信末笔订单号
					jsO.put("tuiOldOrderNumber", tui);//退款订单号
					jsO.put("return_txt", return_Code);//扫码返回数据
					jsO.put("authorizationCode", authorizationCode);//授权码
					jsO.put("referenceNoSuccess", referenceNoSuccess);//订单查询参考号
					jsO.put("oldReferenceNoSuccess", oldReferenceNoSuccess);//订单查询原参考号
					jsO.put("amount", amount);
					jsO.put("acqId", acqId);
					jsO.put("expiredDate", expiredDate);
					jsO.put("settleJson", settleData);
					jsO.put("json", json);
					jsO.put("oldTrace", oldTrace);

				} catch (JSONException e1) {
					e1.printStackTrace();
				}


				ALog.json(jsO.toString());


				if (requestCode == Constants.PAY_WAY_PREAUTH || requestCode == Constants.PAY_WAY_AUTHCOMPLETE) {


					MemberTransAmountResponse member = new MemberTransAmountResponse();
					member.setRealMoney((int) Long.parseLong(amount));
					member.setTradeMoney((int) Long.parseLong(amount));
					CommonFunc.setBackMemberInfo(mContext, member);


					setFlot(jsO.toString(), requestCode);



					//设置流水上送需要上送的参数
					TransUploadRequest request = CommonFunc.setTransUploadData(mContext,printerData,
							CommonFunc.recoveryMemberInfo(mContext),
							CommonFunc.getNewClientSn(mContext),
							printerData.getVoucherNo(), printerData.getReferNo());

					//打印的订单号与流水上送的统一
					printerData.setClientOrderNo(request.getClientOrderNo());

					//流水上送
					transUploadAction1(request);
				}else if (requestCode == Constants.PAY_WAY_AUTHCANCEL){
					setFlot(jsO.toString(), requestCode);

					if (getAuthCode(authorizationCode, Constants.PAY_WAY_PREAUTH)) {
						setTransCancel(requestCode);
					}else{
						ToastUtils.CustomShow(mContext,"本地没查到该交易授权码");
					}

				}else if (requestCode == Constants.PAY_WAY_VOID_AUTHCOMPLETE){
					setFlot(jsO.toString(), requestCode);

					if (getTraceNo(oldTrace, Constants.PAY_WAY_AUTHCOMPLETE)) {
						setTransCancel(requestCode);
					}else{
						ToastUtils.CustomShow(mContext,"本地没查到该交易凭证号");
					}
				}



				break;
		}
	}


	private void setFlot(String data, int requestCode){

		Gson gson = new Gson();
		SmFyResponse smResponse = gson.fromJson(data, SmFyResponse.class);

		printerData.setMerchantName(smResponse.getMerchantName());
		printerData.setMerchantNo(smResponse.getMerchantId());//(transInfo.getMid());
		printerData.setTerminalId(smResponse.getTerminalId());
		printerData.setOperatorNo((String) SPUtils.get(this, Constants.USER_NAME, ""));
//        printerData.setAcquirer(smResponse.getAcqno());
		printerData.setIssuer(smResponse.getIssue());
		printerData.setCardNo(smResponse.getCardNo());
		printerData.setTransType(1 + "");
//        printerData.setExpDate(smResponse.get());
		printerData.setBatchNO(smResponse.getBatchNo());
		printerData.setVoucherNo(smResponse.getTraceNo());
		printerData.setDateTime(
				StringUtils.formatTime(StringUtils.getCurYear()+smResponse.getDate()+smResponse.getTime()));
		printerData.setAuthNo(smResponse.getAuthorizationCode());
		printerData.setReferNo(smResponse.getReferenceNo());
		printerData.setPointCoverMoney(CommonFunc.recoveryMemberInfo(this).getPointCoverMoney());
		printerData.setCouponCoverMoney(CommonFunc.recoveryMemberInfo(this).getCouponCoverMoney());
		printerData.setOrderAmount(CommonFunc.recoveryMemberInfo(this).getTradeMoney());
		printerData.setAmount(StringUtils.formatIntMoney(Long.parseLong(smResponse.getAmount())));
		printerData.setPayType(requestCode);

	}


	/**
	 * 流水上送
	 *
	 * @param request
	 */
	private void transUploadAction1(final TransUploadRequest request) {
		final LoadingDialog dialog = new LoadingDialog(this);
		dialog.show("正在上传交易流水...");
		dialog.setCancelable(false);
		this.sbsAction.transUpload(this, request, new ActionCallbackListener<TransUploadResponse>() {
			@Override
			public void onSuccess(TransUploadResponse data) {

				setTransUpLoadData(request);
				// 设置流水返回的数据
				setTransUpdateResponse(data, dialog, true);
			}

			@Override
			public void onFailure(String errorEvent, String message) {
				dialog.dismiss();
				ToastUtils.CustomShow(mContext, errorEvent + "#" + message);
//				showLayout();

				setTransUpLoadData(request);
				// 设置当前交易流水需要上送
				printerData.setUploadFlag(true);
				printerData.setApp_type(0);


				// 保存打印的数据，不保存图片数据
				PrinterDataSave();

				// 打印
//                Printer.print(printerData, ZfPayPreauthActivity.this);
//                ToolNewLand.getToolNewLand().printText(printerData);
				print(mContext,printerData);
			}


			@Override
			public void onFailurTimeOut(String s, String error_msg) {

			}

			@Override
			public void onLogin() {
//                dialog.dismiss();
//                AppManager.getAppManager().finishAllActivity();



			}
		});
	}


	/**
	 * 保存数据
	 */
	private void PrinterDataSave() {

		CommonFunc.ClearFailureInfo(this);
		CommonFunc.PrinterDataDelete();
		printerData.setStatus(true);
		if (printerData.save()) {
			LogUtils.e("打印数据存储成功");
		} else {
			LogUtils.e("打印数据存储失败");
		}
	}




	protected void setTransUpdateResponse(final TransUploadResponse data, final LoadingDialog dialog, boolean flag) {
		printerData.setPoint_url(data.getPoint_url());
		printerData.setPoint(data.getPoint());
		printerData.setPointCurrent(data.getPointCurrent());
		printerData.setCoupon(data.getCoupon_url());
		setCounponData(data.getCoupon());
		printerData.setBackAmt(data.getBackAmt());
		printerData.setApp_type(0);
		if (flag) {
			// 保存打印的数据，不保存图片数据
			PrinterDataSave();
		}

		//开启线程下载二维码图片
		new Thread(new Runnable() {

			@Override
			public void run() {

				Bitmap point_bitmap = null;
				Bitmap title_bitmap = null;
				if (!StringUtils.isEmpty(data.getPoint_url())) {
					try {
						point_bitmap = Glide.with(getApplicationContext())
								.load(data.getPoint_url())
								.asBitmap()
								.centerCrop()
								.into(Constants.er_width, Constants.er_height).get();

					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
				}

				if (!StringUtils.isEmpty(data.getCoupon_url())) {

					try {
						title_bitmap = Glide.with(getApplicationContext())
								.load(data.getCoupon_url())
								.asBitmap()
								.centerCrop()
								.into(Constants.er_width, Constants.er_height).get();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
				}


				dialog.dismiss();

				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putParcelable("point_bitmap", point_bitmap);
				bundle.putParcelable("title_bitmap", title_bitmap);
				msg.setData(bundle);
				mhandler.sendMessage(msg);

			}
		}).start();

	}


	private void setCounponData(List<Couponsn> data) {
		Gson gson = new GsonBuilder().serializeNulls().create();
		String counponStr = gson.toJson(data);
		printerData.setCouponData(counponStr);
	}



	/**
	 * 撤销流水上送
	 */
	private void setTransCancel(int type) {
		final TransUploadRequest request = new TransUploadRequest();
		String orderId = CommonFunc.getNewClientSn(mContext);
		printerData.setClientOrderNo(orderId);
		printerData.setOldOrderId(orderNo);
		request.setSid(MyApplication.getInstance().getLoginData().getSid());
		request.setAction("2");
		request.setOld_trade_order_num(orderNo);
		request.setNew_trade_order_num(orderId);
		request.setPayType(type);
		request.setAuthCode(printerData.getVoucherNo());
//        request.setClientOrderNo(orderNo);
		request.setT(StringUtils.getdate2TimeStamp(printerData.getDateTime()));

		this.sbsAction.transCancelRefund(this, request, new ActionCallbackListener<String>() {
			@Override
			public void onSuccess(String data) {
//				ToastUtils.CustomShow(mContext, "上传成功");
				printerData.setRefundUpload(true);
				//这个地方用来 在交易记录里去打印用的
				request.setSid(MyApplication.getInstance().getLoginData().getSid());
				// 备份下交易流水数据
				setTransUpLoadData(request);
				printerData.setApp_type(0);



				PrinterDataSave();
				// 打印
//                Printer.print(printerData, ZfPayPreauthActivity.this);
//                ToolNewLand.getToolNewLand().printText(printerData);

				print(mContext,printerData);

			}

			@Override
			public void onFailure(String errorEvent, String message) {
//				ToastUtils.CustomShow(mContext, "上传失败");
				// 备份下交易流水数据
				request.setSid(MyApplication.getInstance().getLoginData().getSid());
				setTransUpLoadData(request);
				// 保存打印的数据，不保存图片数据
				printerData.setApp_type(0);
				PrinterDataSave();
				// 打印
//                Printer.print(printerData, ZfPayPreauthActivity.this);
//                ToolNewLand.getToolNewLand().printText(printerData);

				print(mContext,printerData);
			}

			@Override
			public void onFailurTimeOut(String s, String error_msg) {

			}

			@Override
			public void onLogin() {

			}
		}, true);
	}



	/**
	 * 将流水上送的数据转成字串保存在打印的对象中
	 * 不管成功失败，流水上送的数据保存下来
	 *
	 * @param request
	 */
	private void setTransUpLoadData(TransUploadRequest request) {
		Gson gson = new Gson();
		String data = gson.toJson(request);
		ALog.json(data);
		printerData.setTransUploadData(data);
	}


	/**
	 * 用来返回主线程 打印小票
	 */
	private Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			Bitmap point_bitmap = bundle.getParcelable("point_bitmap");
			Bitmap title_bitmap = bundle.getParcelable("title_bitmap");
			printerData.setPoint_bitmap(point_bitmap);
			printerData.setCoupon_bitmap(title_bitmap);

//			showLayout();

			// 打印
//            Printer.getInstance(ZfPayPreauthActivity.this).print(printerData, ZfPayPreauthActivity.this);
//            ToolNewLand.getToolNewLand().printText(printerData);

			print(mContext,printerData);
		}


	};


	private void print(Context context, SbsPrinterData data){
		if (FyAidlUtils.getPrintService() != null){
			String jsonDate = FyPrintUtils.printText(context, data);
			Log.e("TAG", "json："+jsonDate);
			if (StringUtils.isBlank(jsonDate)){
				return;
			}
			try {
				FyAidlUtils.getPrintService().print(jsonDate);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}



	private boolean getTraceNo(String traceNo, int type) {

		if (StringUtils.isBlank(traceNo)){
			return false;
		}
		// 从交易记录中读取数据
//		allData = DataSupport.order("id desc").limit(100).find(SbsPrinterData.class);
		String where = "payType="+type;
		allData = DataSupport.where(where).find(SbsPrinterData.class);
		if (allData.size() <= 0) {
			ToastUtils.CustomShow(this, "没有交易记录");
			return false;
		}

		// 遍历
		for (int i = 0; i < allData.size(); i++) {
			// 遍历刷卡支付
			if (allData.get(i).getPayType() == type && !StringUtils.isEmpty(allData.get(i).getVoucherNo())) {
				if (StringUtils.isEquals(allData.get(i).getVoucherNo(),traceNo)) {
					//获取交易的订单号
					Gson gson = new Gson();
					TransUploadRequest data = gson.fromJson(allData.get(i).getTransUploadData(), TransUploadRequest.class);

					if (data != null) {
						orderNo = data.getClientOrderNo();
					}
					return true;
				}
			}
		}
		ToastUtils.CustomShow(this, "没有该笔交易");
		return false;
	}


	private boolean getAuthCode(String authCode, int type) {

		// 从交易记录中读取数据
//		allData = DataSupport.order("id desc").limit(100).find(SbsPrinterData.class);
		String where = "payType="+type;
		allData = DataSupport.where(where).find(SbsPrinterData.class);
		if (allData.size() <= 0) {
			ToastUtils.CustomShow(this, "没有交易记录");
			return false;
		}

		// 遍历
		for (int i = 0; i < allData.size(); i++) {
			// 遍历刷卡支付
			if (allData.get(i).getPayType() == type && !StringUtils.isEmpty(allData.get(i).getAuthNo())) {
				if (StringUtils.isEquals(allData.get(i).getAuthNo(),authCode)) {
					//获取交易的订单号
					Gson gson = new Gson();
					TransUploadRequest data = gson.fromJson(allData.get(i).getTransUploadData(), TransUploadRequest.class);

					if (data != null) {
						orderNo = data.getClientOrderNo();
					}
					return true;
				}
			}
		}
		ToastUtils.CustomShow(this, "没有该笔交易");
		return false;
	}

}
